package com.sharer.last.controller;

import com.sharer.last.base.constant.CommonConstant;
import com.sharer.last.base.model.PageVO;
import com.sharer.last.base.model.R;
import com.sharer.last.model.dto.schedule.ScheduleJobChangeDTO;
import com.sharer.last.model.dto.schedule.ScheduleJobQueryDTO;
import com.sharer.last.model.vo.ScheduleJobVO;
import org.springframework.web.bind.annotation.*;
import com.sharer.last.annotation.OperationLogger;
import com.sharer.last.service.ScheduleJobService;

import javax.annotation.Resource;

/**
 * 定时任务动态管理
 *
 * @ClassName ScheduleJobController
 * @Author wangjin
 * @Date 2023/5/5 21:04
 * @Description
 * @Version 1.0
 */
@RestController
@RequestMapping(CommonConstant.BLOG_ADMIN_API + "/schedule/job")
public class ScheduleJobController {
    @Resource
    private ScheduleJobService scheduleJobService;

    /**
     * 分页查询定时任务日志列表
     *
     * @param scheduleJobDTO
     * @return
     */
    @PostMapping("/page")
    public R<PageVO<ScheduleJobVO>> page(@RequestBody ScheduleJobQueryDTO scheduleJobDTO) {
        PageVO<ScheduleJobVO> pageList = scheduleJobService.selectListByPage(scheduleJobDTO);
        return R.success(pageList);
    }

    /**
     * 新建定时任务
     *
     * @param dto
     * @return
     */
    @OperationLogger("新建定时任务")
    @PostMapping("/create")
    public R create(@RequestBody ScheduleJobChangeDTO dto) {
        scheduleJobService.createJob(dto);
        return R.handle();
    }

    /**
     * 修改定时任务
     *
     * @param dto
     * @return
     */
    @OperationLogger("修改定时任务")
    @PutMapping("/update")
    public R update(@RequestBody ScheduleJobChangeDTO dto) {
        scheduleJobService.updateJob(dto);
        return R.handle();
    }

    /**
     * 删除定时任务
     *
     * @param id 任务id
     * @return
     */
    @OperationLogger("删除定时任务")
    @DeleteMapping("/delete")
    public R delete(@RequestParam Long id) {
        scheduleJobService.removeJobById(id);
        return R.handle();
    }

    /**
     * 立即执行任务
     *
     * @param id 任务id
     * @return
     */
    @OperationLogger("立即执行定时任务")
    @GetMapping("/run")
    public R runJob(@RequestParam Long id) {
        scheduleJobService.runJobById(id);
        return R.handle();
    }

    /**
     * 更新任务状态：暂停或恢复
     *
     * @return
     */
    @OperationLogger("更新任务状态")
    @PutMapping("/updateStatus")
    public R updateStatus(@RequestBody ScheduleJobChangeDTO dto) {
        scheduleJobService.updateJobStatusById(dto.getId(), dto.getStatus());
        return R.handle();
    }
}
